package com.example.officialdocumentsys.controller;


import cn.afterturn.easypoi.word.WordExportUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.officialdocumentsys.annotation.LogAnno;
import com.example.officialdocumentsys.common.R;
import com.example.officialdocumentsys.common.ThreadLocalContext;
import com.example.officialdocumentsys.po.*;
import com.example.officialdocumentsys.po.File;
import com.example.officialdocumentsys.service.*;
import com.example.officialdocumentsys.utils.ExportWordUtil;
import com.example.officialdocumentsys.vo.FileVO;
import com.example.officialdocumentsys.vo.LogVO;


import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 文件 前端控制器
 * </p>
 *
 * @author hi
 * @since 2022-11-23
 */
@RestController
@RequestMapping("/file")
public class FileController extends BaseController<File, FileService>{

    @Autowired
    private UserService userService;

    @Autowired
    private FileService fileService;

    @Autowired
    private FiletypeService filetypeService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private OrgService orgService;
    @Value("${bath.file-path}")
    private String basePath;

    @LogAnno(operateType = "浏览文件")
    @GetMapping("/page")
    public R<Page> list(int page, int pageSize, String name) {
        Page<FileVO> pageInfo = new Page(page, pageSize);
        QueryWrapper<FileVO> qw = new QueryWrapper<>();
        return R.success(baseService.getVO(pageInfo,qw));
    }

    @LogAnno(operateType = "浏览文件")
    @GetMapping("/pagePlus")
    public R<Page> pagePlus(int page, int pageSize, Long categoryId,Long typeId,Integer level) {
        Page<FileVO> pageInfo = new Page(page, pageSize);
        QueryWrapper<FileVO> qw = new QueryWrapper<>();
        qw.eq(categoryId != null,"q.c_id",categoryId);
        qw.lambda().eq(typeId != null,FileVO::getTypeId,typeId);
        qw.lambda().eq(level != null,FileVO::getLevel,level);
        qw.lambda().orderByDesc(File::getLevel);
        return R.success(baseService.getVO(pageInfo,qw));
    }

    //列出密级
    @GetMapping("/listLevel")
    public R<List> listAll(){
        QueryWrapper<File> qw = new QueryWrapper<>();
        qw.select("DISTINCT level");
        return R.success(baseService.list(qw));
    }


    @LogAnno(operateType = "上传文件")
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        String fileName = UUID.randomUUID().toString() + substring;

        java.io.File dir = new java.io.File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            file.transferTo(new java.io.File(basePath+fileName));
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return R.success(fileName);
    }


    @LogAnno(operateType = "下载文件")
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response,Integer typeId,Long id) throws Exception {
        User one = userService.getById(ThreadLocalContext.getCurrentId());
        if (one == null){
            return;
        }
        //判断权限
        Integer permissions = one.getPermissions();
        if (typeId != null){
            if (permissions>typeId){
                return;
            }
        }



        try {
            // path是指想要下载的文件的路径
            java.io.File file = new java.io.File(basePath+name);

            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }


    }


    @LogAnno(operateType = "下载文件")
    @GetMapping("/downloadExist")
    public void downloadExist(String name, HttpServletResponse response, Integer typeId, Long id, HttpServletRequest request) throws IOException {
        User one = userService.getById(ThreadLocalContext.getCurrentId());
        if (one == null){
            return;
        }




        File byId = fileService.getById(id);
        //判断权限
        Integer permissions = one.getPermissions();
        if (typeId != null){
            if (permissions>typeId){
                return;
            }
        }

        //生成模板
        String path = "template/" + System.currentTimeMillis()+".pdf";
        PdfDocument pdfDocument = new PdfDocument(new PdfReader("template/template.pdf"), new PdfWriter(path));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, false);
        DeviceRgb color = new DeviceRgb(0, 0, 0);
//        Map<String, String> map = getMap(certificate);
        Map<String,Object> resultListParams =new HashMap<>();
                resultListParams.put("id",byId.getId());
                Filetype byId1 = filetypeService.getById(byId.getTypeId());
                String typeName = byId1.getTypeName();
                if(typeName != null){
                    resultListParams.put("type",typeName);
                }
                resultListParams.put("title",byId.getTitle());
                String s = "";
                for (int i = 0;i<byId.getLevel();i++){
                    s += "★";
                }
                resultListParams.put("level",s);
        Org byId3 = orgService.getById(one.getOrgId());
        resultListParams.put("org",byId3.getOrgName());
                resultListParams.put("remark",byId.getRemark());
                resultListParams.put("time",byId.getInputDate());
        Category byId2 = categoryService.getById(one.getCategoryId());
        resultListParams.put("category",byId2.getCategoryName());
        for (Map.Entry<String, Object> entry : resultListParams.entrySet()) {
            System.out.println(entry);
            try {
                form.getFormFields().get(entry.getKey()).setValue(entry.getValue().toString());
            } catch (Exception e){

            }
        }


        form.flattenFields();
        pdfDocument.close();
        //参数生成后的文件
        java.io.File ssss = null;
            try {
                ssss = new java.io.File(path);
                FileInputStream fileInputStream = new FileInputStream(ssss);
                InputStream fis = new BufferedInputStream(fileInputStream);
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();

                // 清空response
                response.reset();
                // 设置response的Header
                response.setCharacterEncoding("UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(ssss.getPath(), "UTF-8"));
                // 告知浏览器文件的大小
                response.addHeader("Content-Length", "" + ssss.length());
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                outputStream.write(buffer);
                outputStream.flush();
    } catch (Exception e){

            }finally {
                ssss.delete();
            }
    }
    @PostMapping
    public R<String> save(@RequestBody File e) {
        e.setInputDate(LocalDateTime.now());
        e.setFromUser(ThreadLocalContext.getCurrentId());
        baseService.save(e);
        return R.success("保存成功");
    }


}

